import router from './router'
import store from './store'
// eslint-disable-next-line no-unused-vars
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/loginPage'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  console.log('hasToken =>', hasToken)
  if (hasToken) {
    console.log('to.path  => ', to.path)
    if (to.path === '/loginPage') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // TODO huwg
      const hasRoles = store.getters.roles && store.getters.roles.length > 0

      console.log(hasRoles)
      if (hasRoles) {
        next()
      } else {
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch('GetUserInfo')
          .then(res => {
            console.log('GetUserInfo respone = {}', res)
            // 拉取user_info
            // const roles = res.data.roles // note: roles must be a object array! such as: [{id: '1', name: 'editor'}, {id: '2', name: 'developer'}]
            // const menus = res.data.menus;

            store.dispatch('GetMenuList').then(menusResponse => {
              store
                .dispatch('GenerateRoutes', store.getters.menus)
                .then(accessRoutes => {
                  // 根据roles权限生成可访问的路由表
                  router.addRoutes(accessRoutes) // 动态添加可访问路由表
                  console.log('DO GenerateRoutes next => ')
                  next({ ...to, replace: true })
                })
            })
          })
          // eslint-disable-next-line handle-callback-err
          .catch(err => {
            store.dispatch('FedLogOut').then(() => {
              // Message.error(err)
              next(`/loginPage?redirect=dashboard`)
            })
          })
      }
    }
  } else {
    /* has no token*/
    console.log('No Token')
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/loginPage?redirect=dashboard`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
